<template>
  <div style="height:100%;width:100%;position:relative;">
    <div class="pagetop" ref="buttondiv">
      <table class="table1style" border='0' style="font-size:12px;width:100%">
        <tr>
          <td style="width:100px" align="right">报告单类别</td>
          <td>
            <el-select v-model="rptclass" style="width:200px" @change="InitPage" filterable clearable>
              <el-option v-for="(item, index) in rptclassOption" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </td>
          <td style="width:100px" align="right">报告单名称</td>
          <td>
            <el-input v-model="txtrptname" style="width:200px" placeholder="报告单名称" clearable></el-input>
          </td>
          <!-- <td :width="buttonwidth" align="right"></td> -->
        </tr>
        <tr>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td :width="buttonwidth" align="right">
            <el-button icon="el-icon-search" @click.native="InitPage" type="primary" :disabled="changeflag">查询</el-button>
            <el-button icon="el-icon-delete" @click.native="btnDelete" :disabled="changeflag">删除</el-button>
            <el-button icon="el-icon-document" @click.native="btnSave" :disabled="!changeflag">保存</el-button>
            <el-button icon="el-icon-close" @click.native="btnClear" :disabled="!changeflag">取消</el-button>
            <el-button icon="el-icon-setting" @click.native="btnJustify" :disabled="justifyflag">调整</el-button>
            <el-button icon="el-icon-download" @click.native="btnExport">导出</el-button>
            <el-button icon="el-icon-upload2" @click.native="btnImport">导入</el-button>
          </td>
        </tr>
      </table>
    </div>
    <div class="pagecenter">
      <div class="middle-center">
        <vxe-table show-overflow ref="xTable" :data.sync="list" height="auto" :select-config="{ reserve: true }"
          class="mytable-style" :keyboard-config="keyConfig" :keyboard-local-config="keyLocalConfig" border size="mini"
          show-header-overflow highlight-current-row highlight-hover-row resizable stripe @current-change="currentChange"
          :loading="loading" header-align="center" :span-method="rowspanMethod" :cell-class-name="xTableCellClassName"
          :row-class-name="RowClassName" :sort-config="{ trigger: 'cell' }" @cell-dblclick="OpenUsecnt"
          :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true, activeMethod: activeMethod, showIcon: false }">
          <vxe-table-column field="rptclass" title="报告单类别" width="105" sortable></vxe-table-column>
          <vxe-table-column field="rptstylename" title="报告单名称(黑体为系统原始报告)" width="205" sortable></vxe-table-column>
          <vxe-table-column field="rptstyleobject" title="报告单文件名" width="115" sortable>
          </vxe-table-column>
          <vxe-table-column field="rptstyleid" title="报告单ID" width="70" align="center" sortable></vxe-table-column>
          <vxe-table-column field="rptcontentkind" title="对象类别" width="70" align="center" sortable></vxe-table-column>
          <vxe-table-column field="usecnt" title="使用次数(双击查看)" width="90" align="center" sortable>
          </vxe-table-column>
          <vxe-table-column field="lastmodifydt" title="最后修改日期" width="128" sortable></vxe-table-column>
          <vxe-table-column field="description" title="报告单描述" width="175" sortable></vxe-table-column>
          <vxe-table-column field="othertranstype" title="特殊处理方式" width="105" sortable
            :edit-render="{ name: 'select', options: dealOption }">
          </vxe-table-column>
          <vxe-table-column field="nomergeprint" title="不参与合并打印" width="105" align="center" sortable>
            <template v-slot="{ row }">
              <el-checkbox v-model="row.nomergeprint" true-label="1" false-label="0" disabled></el-checkbox>
            </template>
          </vxe-table-column>
        </vxe-table>
      </div>
      <div class="middle-right" v-loading="pageinitloading" element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)">
        <el-tabs type="border-card" style="height:100%;" @tab-click="handleClick">
          <el-tab-pane label="基本信息">
            <el-form ref="form" :model="rptstylelist" label-width="80px">
              <table style="font-size:12px;width:100%" class="table2style">
                <tr>
                  <td align="right">报告单ID</td>
                  <td>
                    <el-input v-model="rptstylelist.rptstyleid" :readonly="onlyread" style="width:100px"></el-input>
                    &nbsp; &nbsp; &nbsp; &nbsp;
                    <el-checkbox true-label="1" false-label="0" v-model="rptstylelist.nomergeprint">不参与合并打印</el-checkbox>

                  </td>
                </tr>
                <tr>
                  <td align="right">报告单类别</td>
                  <td>
                    <el-input v-model="rptstylelist.rptclass" :readonly="onlyread"></el-input>
                  </td>
                </tr>
                <tr>
                  <td align="right" style="color:	#0095D9">报告单名称</td>
                  <td>
                    <el-input v-model="rptstylelist.rptstylename" :readonly="!onlyread" @input="hasChange"></el-input>
                  </td>
                </tr>
                <tr>
                  <td align="right">报告单文件名</td>
                  <td>
                    <el-input v-model="rptstylelist.rptstyleobject" :readonly="onlyread"></el-input>
                  </td>
                </tr>
                <tr>
                  <td align="right">对象类别</td>
                  <td>
                    <el-input v-model="rptstylelist.rptcontentkind" :readonly="onlyread"></el-input>
                  </td>
                </tr>
                <tr>
                  <td align="right">最后修改/加载</td>
                  <td>
                    <el-input v-model="rptstylelist.lastmodifydt" :readonly="onlyread"></el-input>
                  </td>
                </tr>
                <tr>
                  <td align="right" style="color:#0095D9">特殊处理方式</td>
                  <td>
                    <el-select v-model="rptstylelist.othertranstype" style="width:100%" filterable clearable
                      @change="hasChange">
                      <el-option v-for="(item, index) in dealOption" :key="index" :value="item.value" :label="item.label">
                        <span style="float: left">{{ item.label }}</span>
                        <span style="float: right; color: #8492a6; font-size: 13px">{{ item.value }}</span>
                      </el-option>
                    </el-select>
                  </td>
                </tr>
                <tr>
                  <td align="right" style="color:#0095D9">纸张类型</td>
                  <td>
                    <el-input v-model="rptstylelist.papertype" :readonly="!onlyread" @input="hasChange"></el-input>
                  </td>
                </tr>
                <tr>
                  <td align="right" style="vertical-align:top;color:#0095D9">报告单描述</td>
                  <td>
                    <el-input type="textarea" v-model="rptstylelist.description" @input="hasChange" :readonly="!onlyread"
                      :autosize="{ minRows: 12, maxRows: 30 }"></el-input>
                  </td>
                </tr>
              </table>
            </el-form>
          </el-tab-pane>
          <el-tab-pane label="多图片样式转换">
            <div style="height:100%" :key="multiplePiclistkey">
              <vxe-table show-overflow ref="rxTable" height="auto" :select-config="{ reserve: true }"
                :keyboard-config="keyConfig" :keyboard-local-config="keyLocalConfig" :data.sync="multiplePiclist" border
                size="mini" show-header-overflow highlight-current-row highlight-hover-row resizable stripe
                header-align="center" :sort-config="{ trigger: 'cell' }" @cell-dblclick="OpenDialog">
                <vxe-table-column field="seq" title="图片数" width="65" align="center"></vxe-table-column>
                <vxe-table-column field="rptstyleidname" title="报告单样式（双击选择）" width="225"></vxe-table-column>
                <vxe-table-column field="rptstyleid" title="样式ID" width="75" align="center"></vxe-table-column>
                <template v-slot:fix>
                  <div style="font-size:17px;padding:3px;background-color:#fff;font-weight:bold">
                    <el-button @click="AddDetail" class="el-button--310">新增样式</el-button>
                    <el-button @click="DelDetail" class="el-button--310">删除样式</el-button>
                    <div style="color:red;font-size:12px;float:right;line-height:25px">删除时从最多图片数递减删除</div>
                  </div>
                </template>
              </vxe-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>

    <el-dialog width="900px" top="10px" :append-to-body="true" :close-on-click-modal="false" title="报告使用详情"
      :visible.sync="dialogusecnt" :destroy-on-close="true">
      <div style="height:400px" class="mystyle">
        <vxe-table show-overflow ref="xTable" height="auto" :select-config="{ reserve: true }"
          :keyboard-config="keyConfig" :keyboard-local-config="keyLocalConfig" :data.sync="usecntlist" border size="mini"
          show-header-overflow highlight-current-row highlight-hover-row resizable stripe header-align="center"
          :sort-config="{ trigger: 'cell' }" :cell-class-name="cellClassName">
          <vxe-table-column field="rptstyleunitname" title="组合名称/报告单元" width="250" sortable></vxe-table-column>
          <vxe-table-column field="rptstyleenv" title="应用场景" width="125" sortable></vxe-table-column>
          <vxe-table-column field="hospname" title="送检医院" width="175" sortable></vxe-table-column>
          <vxe-table-column field="rptstyleid1" title="样式1" width="80" align="center" sortable></vxe-table-column>
          <vxe-table-column field="rptstyleid2" title="样式2" width="90" align="center" sortable></vxe-table-column>
          <vxe-table-column field="use2linecount" title="使用样式2行数" width="100" align="center" sortable></vxe-table-column>
        </vxe-table>
      </div>
    </el-dialog>
  </div>
</template>

<script type="text/javascript">
import XEUtils from "xe-utils";
XEUtils.mixin({
  // 自定义全局的格式化处理函数
  formatSelect(cellValue, list) {
    let item = list.find((item) => item.value == cellValue);
    return item ? item.label : "";
  },
});

export default {
  name: "MNG120",
  data() {
    return {
      rptclass: "",
      rptclassOption: [],
      txtrptname: "",
      tableData1: [],
      buttonwidth: 0,
      keyConfig: {
        isDel: true,
        isTab: true,
        isEdit: true,
      },
      keyLocalConfig: {
        isArrow: true,
      },
      rptstylelist: {},
      tmprptstylelist: {},
      onlyread: true,
      changeflag: false,
      selrow: [],
      actionindex: "M",
      loading: false,
      pageinitloading: false,
      dialogusecnt: false,
      justifyflag: false,
      usecntlist: [],
      dealOption: [
        { label: "", value: "" },
        { label: "按结果顺序填表", value: "10" },
        { label: "按打印序号填表", value: "20" },
        { label: "多参考值分行", value: "30" },
      ],
      multiplePiclist: [],
      multiplePiclistkey: 0,
    };
  },
  created() {
    this.initOption(); //初始化下拉框的数据
    this.InitPage(); //初始化主列表
  },
  watch: {
    txtrptname(val) {
      if (this.list.length > 0) {
        this.HightLightRow(this.list[0]);
      } else {
        this.HightLightRow(false);
      }
    },
  },
  computed: {
    list() {
      let filterName = this.txtrptname.trim();
      if (filterName) {
        let rest = this.tableData1.filter((item) => {
          return item.rptstylename.toUpperCase().indexOf(filterName.toUpperCase()) > -1;
        });
        return rest;
      } else {
        return this.tableData1;
      }
    },
  },
  mounted() { },
  updated() {
    this.getButtonWidth();
  },
  methods: {
    activeMethod() {
      return false;
    },
    OpenUsecnt({ row, column }) {
      if (column.property == "usecnt") {
        this.$tool
          .request({
            url: "MNG/MNG1/MNG120",
            method: "post",
            data: {
              action: "queryUsecntDetail",
              rptstyleid: row.rptstyleid,
            },
          })
          .then((res) => {
            this.usecntlist = res.data;
            this.dialogusecnt = true;
          })
          .catch((e) => {
            console.log("error", e);
          });
      }
    },
    getButtonWidth() {
      if (this.$refs.buttondiv) {
        this.buttonwidth = this.$refs.buttondiv.offsetWidth - 200 + "px";
      }
    },
    initOption() {
      this.$tool
        .request({
          url: "MNG/MNG1/MNG120",
          method: "post",
          data: {
            action: "initOption",
          },
        })
        .then((res) => {
          this.rptclassOption = res.rptclassOption;
        })
        .catch((e) => {
          console.log("error", e);
        });
    },
    async InitPage() {
      try {
        this.loading = true;
        const res = await this.$tool.request({
          url: "MNG/MNG1/MNG120",
          method: "post",
          data: {
            action: "InitPage",
            RptClass: this.rptclass,
          },
        });
        console.log(res, '2222222222');
        console.log(this.list);

        this.tableData1 = res.Data;
        if (res.Data.length > 0) {
          await this.HightLightRow(res.Data[0]);
        } else {
          this.multiplePiclist = [];
          this.$refs.xTable.setCurrentRow(null);
          this.rptstylelist = {};
          this.selrow = [];
        }
        this.loading = false;
      } catch (e) {
        this.loading = false;
        this.$alert(e);
      }
    },
    async HightLightRow(row) {
      console.log(row);
      if (row) {
        this.selrow = row;
        if (row.rptclass == "LIS.01") {
          this.justifyflag = false;
        } else {
          this.justifyflag = true;
        }
        setTimeout(() => {
          this.$refs.xTable.setCurrentRow(row);
        }, 10);
        await this.QueryLeft(row);
      } else {
        this.selrow = [];
        this.$refs.xTable.setCurrentRow(null);
        this.rptstylelist = {};
        this.tmprptstylelist = {};
      }
    },
    async currentChange({ row }) {
      if (!this.pageinitloading) {
        this.save()
          .then(() => {
            this.HightLightRow(row);
          })
          .catch(() => {
            this.$refs.xTable.setCurrentRow(this.selrow);
          });
      } else {
        this.$refs.xTable.setCurrentRow(this.selrow);
        return;
      }
    },
    async QueryLeft(row) {
      try {
        this.pageinitloading = true;
        const res = await this.$tool.request({
          url: "MNG/MNG1/MNG120",
          method: "post",
          data: {
            action: "QueryLeft",
            rptstyleid: row.rptstyleid,
          },
        });
        this.rptstylelist = res.data[0];
        this.tmprptstylelist = XEUtils.clone(this.rptstylelist, true);
        if (res.multiplePiclist != null && res.multiplePiclist.length > 0) {
          this.multiplePiclist = res.multiplePiclist;
        } else {
          this.multiplePiclist = [];
        }
        this.pageinitloading = false;
      } catch (e) {
        this.pageinitloading = false;
        this.$alert(e);
      }
    },
    save() {
      return new Promise((s, f) => {
        if (!XEUtils.isEqualWith(this.tmprptstylelist, this.rptstylelist) || this.changeflag) {
          //表单被更改
          this.$nextTick(async () => {
            let res = await this.startSave();
            if (res.errcode == "1") {
              this.$pub.message(this, "保存成功！", "success");
              if (this.actionindex == "M")
                await this.setvalueToTable(this.rptstylelist).then((res) => {
                  this.$refs.xTable.setCurrentRow(res);
                  this.$refs.xTable.scrollToRow(res);
                  this.tmprptstylelist = XEUtils.clone(this.rptstylelist, true);
                  this.changeflag = false;
                });
              this.actionindex = "M";
              s();
            } else {
              this.$message.error("保存失败！" + res.errmsg);
              f();
            }
          });
        } else {
          s();
          return;
        }
      });
    },
    async startSave() {
      const res = await this.$tool.request({
        url: "MNG/MNG1/MNG120",
        method: "post",
        data: {
          action: "SaveRecord",
          olddata: this.tmprptstylelist,
          newdata: this.rptstylelist,
          actionindex: this.actionindex,
          data: this.$refs.rxTable.tableData,
        },
      });
      return res;
    },
    setvalueToTable(row) {
      let apromise = new Promise((s, f) => {
        this.selrow.rptstyleid = row.rptstyleid;
        this.selrow.rptclass = row.rptclass;
        this.selrow.rptstylename = row.rptstylename;
        this.selrow.rptstyleobject = row.rptstyleobject;
        this.selrow.rptstylecontent = row.rptstylecontent;
        this.selrow.description = row.description;
        this.selrow.rptcontentkind = row.rptcontentkind;
        this.selrow.lastmodifydt = row.lastmodifydt;
        this.selrow.othertranstype = row.othertranstype;
        this.selrow.nomergeprint = row.nomergeprint;
        s(this.selrow);
      });
      return apromise;
    },
    btnDelete() {
      this.$confirm("您确定删除这条记录吗？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.startDelete();
        })
        .catch(() => { });
    },
    async startDelete() {
      console.log(this.$refs.xTable);
      let delrow = this.$refs.xTable.getCurrentRecord();
      if (delrow) {
        if (Number(delrow.rptstyleid) <= 6000) {
          this.$alert("系统内置基础样式禁止删除！", "信息");
        } else {
          let alld = this.$refs.xTable.tableData;
          let rowindex = alld.indexOf(delrow);
          this.actionindex = "D";
          let res = await this.startSave();
          if (res.errcode == "1") {
            this.$message.success("删除成功！");
            this.actionindex = "M";
            this.$refs.xTable.remove(delrow);
            let havedata = this.$refs.xTable.tableData;
            if (havedata.length > 0) {
              if (rowindex >= havedata.length) rowindex = havedata.length - 1;
              let selectrow = havedata[rowindex];
              await this.HightLightRow(selectrow);
            } else {
              this.$refs.xTable.setCurrentRow(null);
              this.tableData1 = [];
              this.selrow = [];
            }
          } else {
            this.$alert("删除失败！" + res.errmsg, "提示");
          }
        }
      }
    },
    btnSave() {
      this.save();
    },
    btnClear() {
      this.changeflag = false;
      this.QueryLeft(this.selrow);
    },
    btnExport() {
      let p = { prgno: "MNG120", rptstyleid: this.rptstylelist.rptstyleid, rptstylename: this.rptstylelist.rptstylename };
      //let ks = this.rptstylelist.rptstyleid + " " + this.rptstylelist.rptclass + " " + this.rptstylelist.rptstylename + " " + this.rptstylelist.othertranstype;
      let ks = this.rptstylelist.rptstylename + "," + this.rptstylelist.rptclass + "," + this.rptstylelist.othertranstype;
      this.$pub.commexport(this, p, ks + `.repx`);
    },
    //btnLoad() {},
    btnJustify() {
      if (typeof jsObj != "undefined") {
        const rloading = this.$pub.openLoading(this, "样式加载中");
        this.$pub.printreport(this, "", "3", this.selrow.rptstyleid, "", "");
        setTimeout(() => {
          rloading.close();
          // this.loading = false;
        }, 6000);
      } else {
        this.$alert("请使用" + this.$pub.clientname + "打开系统", "提示", {
          confirmButtonText: "确定",
        });
      }
    },
    btnImport() {
      this.$rm_uploadFiles({
        type: "文件上传",
        prgname: "MNG120",
        btn: {
          confirmBtnText: "立即上传",
          cancelBtnText: "取消",
        },
      })
        .then((res) => {
          if (res.flag == "1") {
            this.$alert("文件上传成功", "提示");
            this.InitPage();
          } else {
            this.$alert("文件上传失败" + res.msg, "提示");
          }
        })
        .catch((e) => {
          console.log("error", e);
        });
    },
    // 通用行合并函数（将相同多列数据合并为一行）
    rowspanMethod({ row, $rowIndex, column, data }) {
      let fields = ["rptclass"];
      let cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        let prevRow = data[$rowIndex - 1];
        let nextRow = data[$rowIndex + 1];
        if (prevRow && prevRow[column.property] === cellValue) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            nextRow = data[++countRowspan + $rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },
    RowClassName({ row, rowIndex }) {
      // console.log(row, rowIndex);
      if (row) {
        return 'highlight-row'; // 这里是一个自定义的 CSS 类名
      } else {
        return 'row-modify';
      }
      // let isDirty = this.$refs.xTable.hasRowChange(row);
      // if (isDirty) {
      // return "row-modify";
      // }

    },
    xTableCellClassName({ row, column }) {
      //console.log(row);
      if (column.property == "rptstylename") {
        if (Number(row.rptstyleid) <= 6000) {
          return "col-black";
        }
      }
    },
    hasChange() {
      this.changeflag = true;
    },
    cellClassName({ row, column }) {
      if (column.property == "rptstyleid1") {
        if (row.rptstyleid1 == this.selrow.rptstyleid) {
          return "col-red";
        } else {
          return "";
        }
      }
      if (column.property == "rptstyleid2") {
        if (row.rptstyleid2 == this.selrow.rptstyleid) {
          return "col-red";
        } else {
          return "";
        }
      }
    },
    AddDetail() {
      let oridata = this.$refs.rxTable.tableData;
      let seqlist = XEUtils.max(oridata, (item) => item.seq);
      let maxseq = 1;
      if (!!seqlist) {
        maxseq = seqlist.seq + 1;
      }
      this.$refs.rxTable.insert({ seq: maxseq }).then(({ row }) => {
        this.$refs.rxTable.setCurrentRow(row);
      });
      this.$refs.rxTable.updateListenter();
      this.hasChange();
    },
    DelDetail() {
      let oridata = this.$refs.rxTable.tableData;
      let seqlist = XEUtils.max(oridata, (item) => item.seq);
      //console.log("seqlist", seqlist);
      this.$refs.rxTable.remove(seqlist);
      this.hasChange();
      //var delrow=oridata.filter(item=>item.)
    },
    handleClick(tab, event) {
      this.multiplePiclistkey++;
    },
    OpenDialog({ row, column }) {
      this.$rm_RptunitStyle({
        btn: {
          confirmBtnText: "确定",
          cancelBtnText: "取消",
        },
      })
        .then((res) => {
          // let oridata = this.$refs.rxTable.tableData;
          // let data = oridata.find((m) => (m.rptstyleid == res.code));
          // if (!data) {
          row.rptstyleid = res.code;
          row.rptstyleidname = res.name;
          this.$refs.rxTable.updateListenter();
          this.hasChange();
          // } else {
          //     this.$alert("样式重复选择，请重新选择！");
          // }
        })
        .catch((e) => {
          console.log("error", e);
        });
    },
  },
};
</Script>

<style scoped>
.pagetop {
  width: 100%;
  height: 65px;
  display: -webkit-box;
  -webkit-box-pack: left;
  -webkit-box-align: center;
  border: 1px solid #ccc;
  position: absolute;
  z-index: 99;
}

.pagecenter {
  position: absolute;
  top: 70px;
  width: 100%;
  left: 0;
  bottom: 0px;
  overflow: auto;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 0px;
  right: 405px;
  overflow: auto;
}

.middle-right {
  position: absolute;
  height: 100%;
  width: 400px;
  right: 0px;
  overflow: auto;
}

.table2style tr td {
  padding: 0px 2px 3px 0px;
}

::v-deep .el-checkbox__input.is-disabled+span.el-checkbox__label {
  color: #000000;
  cursor: not-allowed;
}

::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner,
.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner+.el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
}

::v-deep tr.vxe-body--row .row-modify {
  color: blue !important;
}

::v-deep .mytable-style .vxe-body--column .col-black {
  color: black !important;
  font-weight: bolder;
}

::v-deep .mystyle .vxe-body--column .col-red {
  color: red !important;
}

::v-deep .el-button.is-disabled {
  border: 0px;
  color: grey;
  background-color: #e6e6e6;
  font-weight: normal;
}

.table1style tr td:nth-child(odd) {
  text-align: right;
  white-space: nowrap;
  font-size: 12px;
  /*font-weight: bold;*/
  padding: 0px 2px 3px 2px;
}
</style>
